#!/bin/sh

. /usr/share/common

start() {
	echo_title "Configuring LEDs"

	LED_PINS=$(awk -F= '/^gpio_led_/{gsub(/"/, "", $2); print $2}' "$ENV_DUMP_FILE")

	if [ -z "$LED_PINS" ]; then
		echo_warning "No LED pins defined"
		exit 1
	fi

	for pin_raw in $LED_PINS; do
		[ "$pin_raw" = "${pin_raw//[^0-9]/}" ] && pin_raw="${pin_raw}O"
		pin="${pin_raw:0:-1}"
		suffix="${pin_raw:0-1}"
		case "$suffix" in
			o) pin_on=0; pin_off=1 ;;
			O) pin_on=1; pin_off=0 ;;
			*) echo_warning "Pin ${pin} has unknown suffix ${suffix}!" ;;
		esac

		if echo "$gpio_default" | grep -E "\b$pin_raw\b" > /dev/null; then
			echo_info "Set GPIO $pin $pin_on"
			gpio set $pin $pin_on
		else
			echo_info "Set GPIO $pin $pin_off"
			gpio set $pin $pin_off
		fi
	done
}

case "$1" in
	start)
		start
		;;
	stop)
		true
		;;
	restart)
		start
		;;
	*)
		echo "Usage: $0 {start|stop|restart}"
		exit 1
		;;
esac

exit 0
